package com.uenpay.util.net.subscribers;

import com.socks.library.KLog;
import com.uenpay.util.common.App;
import com.uenpay.util.net.Result;
import com.uenpay.util.net.http.HttpParam;
import com.uenpay.util.net.listener.HttpOnNextListener;
import com.uenpay.util.net.listener.HttpResultListener;
import com.uenpay.util.net.retrofit.RetrofitRequest;
import com.uenpay.util.net.retrofit.UenException;

import java.lang.ref.SoftReference;

import rx.Subscriber;

/**
 * 用于在Http请求开始时，自动显示一个ProgressDialog
 * 在Http请求结束是，关闭ProgressDialog
 * 调用者自己对请求数据进行处理
 * Created by liulou on 2016/11/15.
 */
public class UenSubscriber<T> extends Subscriber<T> {

    /*是否弹框*/
    private boolean showPorgress = true;
    //    回调接口
    private HttpResultListener mSubscriberResultListener;
    /*请求数据*/
    private RetrofitRequest api;

    /**
     * 构造
     *
     * @param api
     */
    public UenSubscriber(RetrofitRequest api) {
        this.api = api;
        this.mSubscriberResultListener = api.getHttpListener();
    }

    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        if (mSubscriberResultListener != null) {
            mSubscriberResultListener.onStart();
        }
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onCompleted() {
        if (mSubscriberResultListener != null) {
            mSubscriberResultListener.onComplete();
        }
    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        KLog.e("http error : " + e.getMessage());
        if (mSubscriberResultListener != null) {
            if (e instanceof UenException) {
                App.toast(e.getMessage());
            }
            mSubscriberResultListener.onError(e);
        }
    }

    /**
     * 将onNext方法中的返回结果交给Activity或Fragment自己处理
     *
     * @param t 创建Subscriber时的泛型类型
     */
    @Override
    public void onNext(T t) {
        if (mSubscriberResultListener != null) {
            if (t instanceof Result) {
                String code = ((Result) t).getStatus();
                String msg = ((Result) t).getMsg();
                KLog.d("code-->" + code + " msg--->" + msg);
                if ("0".equals(code)) {
                    if (mSubscriberResultListener instanceof HttpOnNextListener) {
                        ((HttpOnNextListener) mSubscriberResultListener).onNext((((Result) t).getData()));
                    }
                } else {
                    throw (new UenException(msg, code));
                }
            } else {
                throw new UenException("请确认返回数据实体类为Common或String类型");
            }
        } else {
            throw new UenException(HttpParam.RsqMsg.Error);
        }
    }

}